/**
 * 动态代理
 * 为每个类的每个方法添加一个日志功能
 * 通过复制放到对象上实现代理
 * 优点：不污染原型
 * 缺点：占用较多内存，每new一个对象就有一个实例被占用
 */

import { GamePlayer } from "./ProxyStatic";

/**
 * @description 函数代理，方法是挂在原型上的，所以修改方法就得修改原型
 * 如果不修改原型的话，就得把方法挂在当前的对象下，这会占用内存
 * @param _gamePlayer 
 */
function dynamicProxy(_gamePlayer: GamePlayer) {
  let dynamicProxyGamePlayer: GamePlayer = new GamePlayer('');
  Object.keys(_gamePlayer).forEach((_property) => {
    dynamicProxyGamePlayer[_property] = _gamePlayer[_property]
  })
  const _methods = _gamePlayer.__proto__
  Object.keys(_methods).forEach((func) => {
    const _copy = _methods[func];
    dynamicProxyGamePlayer[func] = function () {
      console.log('---' + func + '被动态代理了');
      _copy.call(this)
    }
  })
  _gamePlayer = null // 清空复制的对象
  return dynamicProxyGamePlayer
}

const gamePlayer = new GamePlayer('张三')
const dynamicProxyProtoTypeGamePlayer = dynamicProxy(gamePlayer)
dynamicProxyProtoTypeGamePlayer.login()
dynamicProxyProtoTypeGamePlayer.killBoss()
dynamicProxyProtoTypeGamePlayer.upgrade()
console.log('----------------');

const gamePlayer1 = new GamePlayer('张三1')
gamePlayer1.login()
gamePlayer1.killBoss()
gamePlayer1.upgrade()
